# -*- coding: utf-8 -*-
"""
Created on Thu Nov 26 13:11:31 2020

@author: Administrator
"""

import requests
from time import time, sleep
from random import choice
from json import loads
from urllib.parse import quote
from lxml import etree

novelID = '201'
novelName = '修真世界'
novelName = novelName.encode("unicode-escape").decode().upper().replace("\\U","%u")
sign = str(int(round(time() * 1000)))  # 时间戳

headers = {
    "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 
    "Accept-Encoding":"gzip, deflate, br", 
    "Accept-Language":"zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2", 
    "Connection":"keep-alive", 
    "Host":"www.ting22.com", 
    "Referer":"https://www.ting22.com/", 
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0"
    }
try:
    resp = requests.get(f'https://www.ting22.com/book/{novelID}.html', headers=headers)
    cookie = f'PHPSESSID={resp.cookies["PHPSESSID"]};book_{novelID}={novelName}'
    root = etree.HTML(resp.content)
    url = root.xpath('//li/a[contains(text(),"大结局")]/@href')
except KeyError:
    print("Cookies KeyError!")
    pass
lastChapter = int(url[0][url[0].rfind(novelID)+len(novelID)+1:-5])
for cid in range(1,lastChapter+1):
    headers["Accept"]="application/json, text/javascript, */*; q=0.01"
    headers["Host"]="mp3.huanting.cc:13866"
    headers["Origin"]="https://www.ting22.com"
    headers["Referer"]="https://www.ting22.com/"
    resp = requests.get('https://mp3.huanting.cc:13866/key.php', headers=headers)
    json_str = resp.text
    json_data = loads(json_str)
    headers["Accept"]="*/*"
    headers["Referer"]= "https://www.ting22.com/ting/{novelID}-{str(cid)}.html"
    headers["Cookie"]= cookie+'%7Chttps%3A//www.ting22.com/book/{novelID}.html^%u7B2C{cid}%u96C6%7Chttps%3A//www.ting22.com/ting/{novelID}-{cid}.html_$_|; index_setID=_$_|'
    headers["s1"]="d494b1d59cdaef3f"
    headers["s2"]=json_data["key"]
    headers["X-Requested-With"]="XMLHttpRequest"
    response = requests.get(
        #"https://www.ting22.com/api.php?c=Json&id="+novelID+"&page="+str(rl+1)+"&pagesize=10&callback=jQuery21403942595757035292_{}&_={}".format(sign, sign), headers=headers
        f'https://www.ting22.com/api3.php?id={novelID}&pid={cid}', headers=headers
        )
    
    json_str = response.text
    json_str = json_str.encode('raw_unicode_escape').decode('raw_unicode_escape').replace(r'\/\/', '//').replace(r'\/', '/')
    print('jsonStr:',json_str[41:-2])
    json_data = loads(json_str)#[json_str.index('({')+1:-2])
    #cookie[novelID+'_setNAME'] = quote(novelName)+'('+quote(json_data["playlist"][0]["trackName"].split('(')[1][:-1])+')'+quote(' 第{}章'.format(rl*10+10))
    mp4_url_list = [x["file"] for x in json_data["playlist"]]
    #print(json_data["playlist"][0]["trackName"].split('(')[1][:-1])
    name_list = [x["pid"] for x in json_data["playlist"]]
    mp4_real_url_list = [''.join(map(chr, [int(i) for i in s.split("*")])) for s in mp4_url_list]
    
    print(mp4_real_url_list)
    print(name_list)
    
    for i in range(len(mp4_url_list)):
        mp4 = requests.get(mp4_real_url_list[i])
        with open('./'+novelName+'/'+str(name_list[i])+'.mp3',"wb") as f:
            f.write(mp4.content)
            f.close()
            print('{}.mp3 -- 下载完成！'.format(name_list[i]))
            
    sleep(choice([0.3, 0.5, 0.8, 1.1, 1.5, 1.8, 2, 2.3, 2.5]))

import os
print(os.listdir("./"+novelName))

def get_dir_size(dir_path):
    file_list = os.listdir(dir_path)
    size = 0
    for file_name in file_list:
        size += os.path.getsize(dir_path + "/" + file_name)
    return round(size / 1024 / 1024, 2)

print('{} MB'.format(get_dir_size("./"+novelName)))
